package com.ftwj.demo.utils.captcha.annation;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ftwj.demo.utils.captcha.utils.CaptchaUtil;
import com.ftwj.demo.utils.exception.ValidateFailedException;

import cn.hutool.core.util.ReflectUtil;

/**
 * 
 * @ClassName: WebLogAcpect
 * @Description: AOP验证码校验
 * @author: WangShengLi
 * @date: 2019年7月12日 下午2:53:19
 */
@Aspect
@Component
//@Order
public class CaptchaAcpect {

	/**
     * 	定义切入点，切入点为com.example.aop下的所有函数
     */
    //@Pointcut("execution(public * com.ftwj.*.controller.*Controller..*(..))")
    @Pointcut("@annotation(Captchar)")
    public void webLog(){
    	
    }

    /**
     * 	前置通知：在连接点之前执行的通知
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Method method = ReflectUtil.getMethodByName(Class.forName(joinPoint.getSignature().getDeclaringTypeName()), joinPoint.getSignature().getName());
        Captchar captchar = method.getAnnotation(Captchar.class);
        String name=captchar.name();
        String captcha=request.getParameter(name);
        captchaValidation(request, captcha);
    }
    
    public Boolean captchaValidation(HttpServletRequest request,String captcha) {
    	if (!CaptchaUtil.ver(captcha, request)) {
            throw new ValidateFailedException("captche:图形验证码验证失败！");
        }
    	CaptchaUtil.clear(request);  // 清除session中的验证码
    	return true;
    }
    
}
